<?php
/* 
 * 网站日志统计
 */
class WeblogAction extends CommonAction {

public function _filter(&$map) {
        //TODO
        $key = trim($_REQUEST['keywords']);
        if(!empty($key)) {
                $where['Sale_detail.sale_title'] = array('like',"%".$key."%");//产品名称
               // $where['Sale.customer_name'] = array('like',"%".$key."%");//产品名称
               // $where['Sale.shipping_name'] = array('like',"%".$key."%"); 
               // $where['Sale.logino'] = array('like',"%".$key."%");
               // $where['Sale.address'] = array('like',"%".$key."%");
               // $where['Sale.mobile'] = array('like',"%".$key."%");
               // $where['Sale.phone'] = array('like',"%".$key."%");
               // $where['Sale.remark'] = array('like',"%".$key."%");
            
            $where['_logic'] = "or";
            $map['_complex'] = $where;
        }
        if(!empty($_REQUEST['src_id'])) {
              $map['src_id'] = trim($_REQUEST['src_id']);
        }

        if( $_REQUEST['remark'] != '' )
          $map['remark'] = trim($_REQUEST['remark']);

        if( $_REQUEST['baobei_id'] != '' )
          $map['baobei_id'] = trim($_REQUEST['baobei_id']);

        if( $_REQUEST['ip'] != '' )
          $map['ip'] = array('like',"%".trim($_REQUEST['ip'])."%");

        if( $_REQUEST['url'] != '' )
          $map['url'] = array('like',"%".trim($_REQUEST['url'])."%");
        if( $_REQUEST['ref'] != '' )
          $map['ref'] = array('like',"%".trim($_REQUEST['ref'])."%");

        if( $_REQUEST['search_key'] != '' )
          $map['search_key'] = array('like',"%".trim($_REQUEST['search_key'])."%");

        if( $_REQUEST['user_day_no'] != '' )
          $map['user_day_no'] = array('like',"%".trim($_REQUEST['user_day_no'])."%");

        if( $_REQUEST['address'] != '' )
          $map['location_name'] = array('like',"%".trim($_REQUEST['address'])."%");

        if( $_REQUEST['title'] != '' )
          $map['title'] = array('like',"%".trim($_REQUEST['title'])."%");
        if( $_REQUEST['order_source_id'] != '' )
          $map['order_source_id'] = $_REQUEST['order_source_id'];
        //time 
        $cond_time = array();
        if( $_REQUEST['start_time'] != '' )
          array_push($cond_time, array( 'egt' , strtotime($_REQUEST['start_time']) ) );
          //$cond_time = array( 'egt' , strtotime($_REQUEST['start_time']) );
        if( $_REQUEST['end_time'] != '' )
          array_push($cond_time, array( 'elt' , strtotime($_REQUEST['end_time']) ) );

        //选择了时间类型,并且时间不为空，则按时间进行搜索
        if( $_REQUEST['time_type'] != "" && 
          ($_REQUEST['end_time'] != '' ||  $_REQUEST['start_time'] != '' ) ){
            switch ($_REQUEST['time_type']) {
              case '3': //时间
                  $map['create_time '] = $cond_time;
                break;
              case '4': //支付时间
                $map['pay_time '] = $cond_time;
                break;
              default:  //按下单时间查询
                $map['create_time '] = $cond_time;
                break;
            }
            
        }

    }
 
   //历史数据查询
   public function archive(){
       parent::index('Weblog_archive');
       
   }


/**获取各店铺内的量子统计实时数据
*@order_source_id 店铺
*@$limit  每页显示的记录数
*@start_page 开始查询的页数
**/
public static function getLZLog($order_source_id = 5,$limit=25,$start_page = 1){
    $offset = $limit*($start_page-1); //查询的起始记录数，结合limit表示第几页的数据起始点
    $click_page = 22+($start_page - 1);//JS click count,start from 22
    $source_key = self::getSourceKey($order_source_id);

    $ch = curl_init();
    $url = "http://api.linezing.com/=/view/recent/~/~?p4p=0&limit=".$limit."&offset=".$offset."&_s=".$source_key."&_c=OR.C%5B".$click_page."%5D";
    $refer_url = "http://lz.taobao.com/";
    $user_agent = "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36";
      $options = array(
                  CURLOPT_URL => $url,
                  CURLOPT_HEADER => 0,
                  //CURLOPT_HTTPHEADER => $header,
                  CURLOPT_REFERER => $refer_url,
                  CURLOPT_USERAGENT => $user_agent,
                  CURLOPT_NOBODY => 0,
                  CURLOPT_PORT => 80,
                  CURLOPT_RETURNTRANSFER => 1, //1 return no grab content
                  CURLOPT_FOLLOWLOCATION => 1,
                  //CURLOPT_COOKIEJAR =>  $cookie_file, //必须使用jar
                  //CURLOPT_COOKIEFILE => $cookie_file,
                  CURLOPT_TIMEOUT => 300
              );
 
  curl_setopt_array($ch, $options);
  $result = curl_exec($ch);
  $result = preg_replace("/OR\.C\[(\d+)\]\(/","",$result);
  $result = str_replace(");","",$result);
  $s_result = json_decode($result,true);
  $log_data = $s_result['1'];
  if(!is_array($log_data)){
      curl_close($ch);
      $subject = $order_source_id."量子日志无法获取";
      $message = "店铺".$order_source_id."量子日志出现问题，赶快更新KEY  ";
      $from = "mikegao<mikegao@dayanwo.com>";
      $to = "chaorengao@139.com";
      sendMail($subject,$message,$from,$to) ;
      return;
  }
  $new_log = array();
  $new_value = array();
  $today = date("Y-m-d");
  foreach ($log_data as $key => $value) {
    $ctime = strtotime($today." ".$value['log_time']); //day如果取淘宝的记录，会有偏差
    if($ctime > (time()+20) ) //如果制造的时间超过当前时间，则减去24小时，防止凌晨抓取时时间不正确的问题
      $ctime = ($ctime-24*60*60);
    $t = parse_url($value['ref']);
    $query = self::convertUrlQuery($t['query']);  //解析参数
    $searckh_key = (!empty($query['q']))? ( detect_encoding( urldecode($query['q'] ),'utf-8') ) : ""; //搜索关键词
    $searckh_key2 = (!empty($query['wq']))?detect_encoding( urldecode($query['wq']),'utf-8' ) : ""; //搜索关键词
    $searckh_key = (!empty($searckh_key2))? $searckh_key.";".$searckh_key2 : $searckh_key;
    if(!empty($query['keyword']))
    	$searckh_key .="; ". detect_encoding( urldecode($query['keyword']),'utf-8' ); //搜索关键词

    //14-08-11修正淘宝14-08-08正式全面启动95095医药馆网站后,宝贝ID无法正确识别的问题,如果取不到宝贝ID,则取原hash值
    $baobei_id = self::getBaobeiId($value['url']);
    $baobei_id = $baobei_id > 0 ? $baobei_id : $value['url_baobei_id'];
    $new_value = array(
        'create_time' => $ctime,
        'ip' => $value['ip'],
        'uv_no' => $ctime.$value['uv_no'],
        'ref' => $value['ref'],
        'url' => $value['url'],
        'is_baobei' => $value['is_baobei'],
        'location_id' => $value['location_id'],
        'location_name' => $value['location_name'],
        'user_day_no' => $value['uv_no'],
        'search_key' => empty($searckh_key)?'':$searckh_key, 
        'ref_type' => $value['ref_type'],
        'title' => $value['title'],
        'baobei_id' => $baobei_id,
        'uv_return' => $value['uv_return'],
        'src_id' => $value['src_id'],
        //'time' => $value['log_time'],
        'order_source_id' => $order_source_id,
        //'remark' => $t['query'],
      );
    $new_log[$key] = $new_value;
    unset($new_value);
  }
  krsort($new_log); //倒序排列，时间最新的最后插入数据库
  $new_log = array_values($new_log);
  curl_close($ch);
  return $new_log;
}

/** 插入日志，插入前需要去重
*@resutl 获取到的日志数组
**/
public static function insertLog($result = array()){
    if(empty($result))
      return;
    $tmp_uvno = array();
    foreach ($result as $key => $value) {
        $tmp_uvno[$value['uv_no']] = $value['uv_no'];
    }
    $map['uv_no'] = array('in',$tmp_uvno);
    $exist_uvnos = M('Weblog')->where($map)->getField('id,uv_no');
    //存在重复日志记录，则去重
    if(count($exist_uvnos) > 0 ){
        foreach ($result as $k=> $v) {
           if(array_search($v['uv_no'], $exist_uvnos) !== false )
              unset($result[$k]); //重置重复的日志记录
        }
    }
    //splite array with 100 length
    $result_length = count($result);
    if($result_length > 100 ){
       $length = ceil($result_length/100);
       $slice_log = array();
       for($i=0;$i<$length;$i++){
           unset($slice_log);
          $slice_log = array_slice($result,$i*100,100);
          if(count($slice_log) >0 );
            M('Weblog')->addAll(array_values($slice_log) );  //插入新日志
       }
    }else{
        $result = array_values($result); //rebuild index
        if($result);
            M('Weblog')->addAll($result);  //插入新日志
    }
}

/**
**/
public static function getAllLog(){
    //每家店铺取10个页面，即能取到1000条数据
  //德生堂
  $result = array();
  for ($i=0; $i < 1; $i++) {
      unset($result);
      $result = self::getLZLog($order_sorce_id = 5,$limit=1000,$i+1);
      self::insertLog($result);
      sleep(3);
  }
  for ($i=0; $i < 1; $i++) { //京卫
      unset($result);
      $result = self::getLZLog($order_sorce_id = 3,$limit=1000,$i+1);
      self::insertLog($result);
      sleep(3);
  }
  /*14-03-27关掉日志
  for ($i=0; $i < 1; $i++) { //亚洲
      unset($result);
      $result = self::getLZLog($order_sorce_id = 7,$limit=1000,$i+1);
      self::insertLog($result);
  }
  */

}

public function sale_trend(){
  if( empty($_REQUEST['item_id']) ){
      $this->display();
      return;
  }
  else{
      if(empty($_REQUEST['order_source_id']))
          $_REQUEST['order_source_id'] = M('Weblog')->where('baobei_id = '.trim($_REQUEST['item_id']))->getField('order_source_id');
      $trend_data = $this->getSaleTrend($_REQUEST['order_source_id'],$_REQUEST['item_id'],$_REQUEST['start_date'],$_REQUEST['end_date'],$_REQUEST['is_mobile'] );
      $product = $this->getProductDetail($_REQUEST['order_source_id'],$_REQUEST['item_id']);
      $this->assign('product',$product);
      $this->assign('trend_data',$trend_data);
      $this->display();
      }
}

public function search_review(){
  if(empty($_REQUEST['order_source_id']) || empty($_REQUEST['item_id']) ){
      $this->display();
      return;
  }
  else{
      $search_data = $this->getSearchLog($_REQUEST['order_source_id'],$_REQUEST['item_id'],$_REQUEST['start_date'],$_REQUEST['end_date'] );
      $product = $this->getProductDetail($_REQUEST['order_source_id'],$_REQUEST['item_id']);
      $searchTrend = $this->getSearchTrend($_REQUEST['order_source_id'],$_REQUEST['item_id'],$_REQUEST['start_date'],$_REQUEST['end_date']);
      $this->assign('product',$product);
      $this->assign('source_key',$this->getSourceKey($_REQUEST['order_source_id']));
      $this->assign('search_trend',$searchTrend);
      $this->assign('search_data',$search_data);
      $this->display();
      }
}
/**
**获取淘宝某个商品的销量，访问量趋势数据
**@order_source_id 订单来源
**@item_id 商品淘宝编号
**@start_date 查询的起始日期，格式为 2014-03-12
**@end_date 查询的截止日期，默认为昨天
**@is_mobile 是否手机端,默认PC
**/
public  function getSaleTrend($order_source_id = 5,$item_id="",$start_date = "",$end_date="",$is_mobile=0){
    if(empty($order_source_id) || empty($item_id) )
        $this->error("请输入订单来源或宝贝编号！");
    if(empty($start_date))
        $start_date = toDate((time()-24*60*60*30),'Y-m-d');
    if(empty($end_date))
        $end_date = toDate((time()-24*60*60),'Y-m-d');
 
    $source_key = $this->getSourceKey($order_source_id);

    $ch = curl_init();
    if($is_mobile)
        $url = "http://api.linezing.com/=/view/mobile/sale/itemdailysell_trend?aucid=".$item_id."&days=".$start_date."..".$end_date."&_s=".$source_key."&&_c=OR.C%5B30%5D&sort=day&dir=asc"; //手机端按时间升序排
    else
        $url = "http://api.linezing.com/=/view/itemdailysell/type/trend?qid=".$item_id."&days=".$start_date."..".$end_date."&_s=".$source_key."&&_c=OR.C%5B30%5D";
        $refer_url = "http://lz.taobao.com/";
    $user_agent = "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36";
      $options = array(
                  CURLOPT_URL => $url,
                  CURLOPT_HEADER => 0,
                  //CURLOPT_HTTPHEADER => $header,
                  CURLOPT_REFERER => $refer_url,
                  CURLOPT_USERAGENT => $user_agent,
                  CURLOPT_NOBODY => 0,
                  CURLOPT_PORT => 80,
                  CURLOPT_RETURNTRANSFER => 1, //1 return no grab content
                  CURLOPT_FOLLOWLOCATION => 1,
                  //CURLOPT_COOKIEJAR =>  $cookie_file, //必须使用jar
                  //CURLOPT_COOKIEFILE => $cookie_file,
                  CURLOPT_TIMEOUT => 300
              );
 
  curl_setopt_array($ch, $options);
  $result = curl_exec($ch);
  $result = preg_replace("/OR\.C\[(\d+)\]\(/","",$result);
  $result = str_replace(");","",$result);
  $s_result = json_decode($result,true);
  $log_data = $s_result['1'];
  if(!is_array($log_data)){
      curl_close($ch);
      $subject = $order_source_id."量子日志无法获取";
      $message = "店铺".$order_source_id."宝贝销量趋势无法获取，赶快更新KEY  ";
      $from = "mikegao<mikegao@dayanwo.com>";
      $to = "chaorengao@139.com";
      sendMail($subject,$message,$from,$to) ;
      return;
  }
  curl_close($ch);
  return $s_result;
}


/**
**获取淘宝某个商品的搜索数据
**@order_source_id 订单来源
**@item_id 商品淘宝编号
**@start_date 查询的起始日期，格式为 2014-03-12
**@end_date 查询的截止日期，默认为昨天
**/
public  function getSearchLog($order_source_id = 5,$item_id="",$start_date = "",$end_date=""){
    if(empty($order_source_id) || empty($item_id) )
        $this->error("请输入订单来源或宝贝编号！");
    if(empty($start_date))
        $start_date = toDate((time()-24*60*60*30),'Y-m-d');
    if(empty($end_date))
        $end_date = toDate((time()-24*60*60),'Y-m-d');
 
    $source_key = $this->getSourceKey($order_source_id);

    $ch = curl_init();
    $url = "http://api.linezing.com/=/view/standard/search/itemkey?date=".$end_date."&order=click&sort=desc&offset=0&item=".$item_id."&_s=".$source_key;  //"&_c=OR.C%5B100%5D";
    $refer_url = "http://lz.taobao.com/";
    $user_agent = "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36";
      $options = array(
                  CURLOPT_URL => $url,
                  CURLOPT_HEADER => 0,
                  //CURLOPT_HTTPHEADER => $header,
                  CURLOPT_REFERER => $refer_url,
                  CURLOPT_USERAGENT => $user_agent,
                  CURLOPT_NOBODY => 0,
                  CURLOPT_PORT => 80,
                  CURLOPT_RETURNTRANSFER => 1, //1 return no grab content
                  CURLOPT_FOLLOWLOCATION => 1,
                  //CURLOPT_COOKIEJAR =>  $cookie_file, //必须使用jar
                  //CURLOPT_COOKIEFILE => $cookie_file,
                  CURLOPT_TIMEOUT => 300
              );
 
  curl_setopt_array($ch, $options);
  $result = curl_exec($ch);
  $result = preg_replace("/OR\.C\[(\d+)\]\(/","",$result);
  $result = str_replace(");","",$result);
  $s_result = json_decode($result,true);
  $log_data = $s_result['list'];
  curl_close($ch);
  return $log_data;
}

/**
**获取淘宝某个商品的平均搜索排名及平均转化率－－在某个时间范围内
**@order_source_id 订单来源
**@item_id 商品淘宝编号
**@start_date 查询的起始日期，格式为 2014-03-12
**@end_date 查询的截止日期，默认为昨天
**/
public  function getSearchTrend($order_source_id = 5,$item_id="",$start_date = "",$end_date=""){
    if(empty($order_source_id) || empty($item_id) )
        $this->error("请输入订单来源或宝贝编号！");
    if(empty($start_date))
        $start_date = toDate((time()-24*60*60*30),'Y-m-d');
    if(empty($end_date))
        $end_date = toDate((time()-24*60*60),'Y-m-d');
 
    $source_key = $this->getSourceKey($order_source_id);

    $ch = curl_init();
    $url = "http://api.linezing.com/=/view/standard/search/presentitem?days=".$start_date."..".$end_date."&item=".$item_id."&_s=".$source_key;  //"&_c=OR.C%5B100%5D";
    $refer_url = "http://lz.taobao.com/";
    $user_agent = "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36";
      $options = array(
                  CURLOPT_URL => $url,
                  CURLOPT_HEADER => 0,
                  CURLOPT_REFERER => $refer_url,
                  CURLOPT_USERAGENT => $user_agent,
                  CURLOPT_NOBODY => 0,
                  CURLOPT_PORT => 80,
                  CURLOPT_RETURNTRANSFER => 1, //1 return no grab content
                  CURLOPT_FOLLOWLOCATION => 1,
                  CURLOPT_TIMEOUT => 300
              );
 
  curl_setopt_array($ch, $options);
  $result = curl_exec($ch);
  $result = preg_replace("/OR\.C\[(\d+)\]\(/","",$result);
  $result = str_replace(");","",$result);
  $s_result = json_decode($result,true);
  $log_data = $s_result['list'];
  curl_close($ch);
  return $log_data;
}

/**
**获取淘宝某个商品的名称，图片，价格，上架时间等。
**@order_source_id 订单来源
**@item_id 商品淘宝编号
**/
public function getProductDetail($order_sorce_id = 5,$item_id=""){
    if(empty($order_sorce_id) || empty($item_id) )
        $this->error("请输入订单来源或宝贝编号！");
 
    $source_key = 0;
    switch ($order_sorce_id) {
      case '5': //德生堂
        $source_key = M('Configure')->where('var_name = "dst_key"')->getField('value');
        $nick = "德生堂大药房旗舰店";
        break;
      case '3': //京卫
        $source_key = M('Configure')->where('var_name = "jw_key"')->getField('value');
        $nick = "京卫大药房旗舰店";
        break;
      case '7': //亚洲
        $source_key = M('Configure')->where('var_name = "yazhou_key"')->getField('value');
        $nick = "亚洲大药房旗舰店";
        break;
      default:
        break;
    }

    $ch = curl_init();
    $url = "http://api.linezing.com/=/view/itempic/~/~?item=".$item_id."&nick=".$nick."&_s=".$source_key."&_c=OR.C%5B8%5D";
    $refer_url = "http://lz.taobao.com/";
    $user_agent = "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36";
      $options = array(
                  CURLOPT_URL => $url,
                  CURLOPT_HEADER => 0,
                  //CURLOPT_HTTPHEADER => $header,
                  CURLOPT_REFERER => $refer_url,
                  CURLOPT_USERAGENT => $user_agent,
                  CURLOPT_NOBODY => 0,
                  CURLOPT_PORT => 80,
                  CURLOPT_RETURNTRANSFER => 1, //1 return no grab content
                  CURLOPT_FOLLOWLOCATION => 1,
                  //CURLOPT_COOKIEJAR =>  $cookie_file, //必须使用jar
                  //CURLOPT_COOKIEFILE => $cookie_file,
                  CURLOPT_TIMEOUT => 300
              );
 
  curl_setopt_array($ch, $options);
  $result = curl_exec($ch);
  $result = preg_replace("/OR\.C\[(\d+)\]\(/","",$result);
  $result = str_replace(");","",$result);
  $s_result = json_decode($result,true);
  curl_close($ch);
  return $s_result;
}

  /** 
 * Returns the url query as associative array 
 * 
 * @param    string    query 
 * @return    array    params 
 */ 
private static function convertUrlQuery($query)
{ 
    $queryParts = explode('&', $query); 
    
    $params = array(); 
    foreach ($queryParts as $param) 
  { 
        $item = explode('=', $param); 
        $params[$item[0]] = $item[1]; 
    } 
    
    return $params; 
}

/**
 *get baobei_id from taobao visit url like 95095,if not ,return 0;
 *@url visit url
 */
public static function getBaobeiId($url){
   $query = parse_url($url);
   $t = self::convertUrlQuery($query['query']);
   $baobei_id = $t['id'] > 0 ? $t['id'] : 0;
   return $baobei_id;
}

 //get taobao key by order_source_id 
 private function getSourceKey($order_source_id = 0){

    switch ($order_source_id) {
      case "5": //德生堂
        $source_key = M('Configure')->where('var_name = "dst_key"')->getField('value');
        $nick = "德生堂大药房旗舰店";
        break;
      case '3': //京卫
        $source_key = M('Configure')->where('var_name = "jw_key"')->getField('value');
        $nick = "京卫大药房旗舰店";
        break;
      case '7': //亚洲
        $source_key = M('Configure')->where('var_name = "yazhou_key"')->getField('value');
        $nick = "亚洲大药房旗舰店";
        break;
      default:
        $source_key = 0;
        break;
    }
     return $source_key;
 }


}

?>
